<template>
    <el-dialog ref="dialog" class="dialog-form" title="更新进度" destroy-on-close :visible.sync="visible" width="500px" :before-close="handleCancel">
         <el-form ref="dialogForm" :model="form" size="medium" :rules="rules" label-width="112px" @submit.native.prevent>
            <el-form-item label="归属计划周期" prop="date">
                <el-date-picker
                    v-model="form.date"
                    type="month"
                    value-format="yyyy-M"
                    :editable="false"
                    :picker-options="pickerOptions"
                    placeholder="请选择"
                    style="width: 100%;"
                    @change="handleChange"
                />
            </el-form-item>
            <el-form-item label="对齐项目" prop="projectId">
                <el-select
                    v-model="form.projectId"
                    :disabled="projectDisabled"
                    clearable
                    placeholder="请选择"
                    style="width: 100%;"
                    @change="getProjectName"
                >
                    <el-option
                        v-for="item in projectOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="完成进度" prop="progress">
                <el-input
                    v-model.number.trim="form.progress"
                    clearable
                    autocomplete="off"
                    placeholder="请输入"
                    maxlength="50"
                >
                    <span slot="suffix" class="el-input__unit input-unit">%</span>
                </el-input>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select
                    v-model="form.status"
                    clearable
                    placeholder="请选择"
                    style="width: 100%;"
                >
                    <el-option
                        v-for="item in projectStatus"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="实施情况" prop="implementation">
                <el-input
                    v-model.trim="form.implementation"
                    type="textarea"
                    clearable
                    placeholder="请输入"
                    maxlength="200"
                    show-word-limit
                    :autosize="{ minRows: 3 }"
                />
            </el-form-item>
            <el-form-item label="已完成工程量" prop="completedAmount">
                <el-input
                    v-model.trim="form.completedAmount"
                    clearable
                    placeholder="支持小数点后2位"
                    maxlength="50"
                >
                    <span slot="suffix" class="el-input__unit input-unit">{{ form.arithmeticalUnit }}</span>
                </el-input>
            </el-form-item>
            <el-form-item label="金额" prop="money">
                <el-input
                    v-model.trim="form.money"
                    type="number"
                    clearable
                    placeholder="支持小数点后6位"
                    maxlength="50"
                >
                    <span slot="suffix" class="el-input__unit input-unit">元</span>
                </el-input>
            </el-form-item>
         </el-form>
        
        <div slot="footer" class="dialog-footer">
            <BaseButton type="second" :throttle-time="200" @click="handleCancel">取 消</BaseButton>
            <BaseButton :loading="submitLoading" :throttle-time="200" @click="handleAdd">确 定</BaseButton>
        </div>
    </el-dialog>
</template>

<script>
import { isNumber2, isNumber6 } from '@/utils/validate'

import { MaintenanceProjectModel, ProjectProgressModel } from '@/models'
import { ProjectStatus } from '../../../constants'

export default {
    name: 'UpdateProgress',
    props: {
        visible: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            projectStatus: ProjectStatus,
            model: new MaintenanceProjectModel(),
            progressModel: new ProjectProgressModel(),
            submitLoading: false,
            props: {
                value: 'id',
                label: 'name'
            },
            pickerOptions: {},
            projectOptions: [],
            projectDisabled: true,
            form: {},
            rules: {
                date: [{ required: true, message: '请选择周期', trigger: ['blur', 'change'] }],
                projectId: [{ required: true, message: '请选择对齐计划', trigger: ['blur', 'change'] }],
                progress: [
                    { required: true, message: '请输入完成进度', trigger: 'blur' },
                    { validator: this.validNum, trigger: 'blur' }
                ],
                status: [{ required: true, message: '请选择状态', trigger: ['blur', 'change'] }],
                completedAmount: [{ validator: this.validNum2, trigger: 'blur' }],
                money: [{ validator: this.validNum6, trigger: 'blur' }]
            },
            info: {}
        }
    },
    methods: {
        handleChange(val) {
            if (val) {
                this.projectOptions = []
                this.projectDisabled = false
                const date = val.split('-')
                this.form.year = date[0]
                this.form.month = date[1]
                this.setProjectOptions()
            } else {
                this.projectDisabled = true
            }
        },
        getProjectName(val) {
            if (!val) { return }           
            this.projectOptions.some(item => {
                if (item.id === val) {
                    this.form.projectName = item.name
                    return true
                }
            })
        },
        handleDisabledDate(roadCode) {
            this.model.getEnablePlan({ roadCode }).then(res => {
                this.pickerOptions = {
                    disabledDate(time) {
                        // 如果查询的计划一个都没有，直接全部禁掉
                        if (res.length === 0) {
                            return true
                        }
                        
                        const year = time.getFullYear()
                        const month = time.getMonth() + 1
                        let result = true
                        
                        res.some(item => {
                            if (Number(item.year) === year && Number(item.month) === month) {
                                result = false
                                return true
                            }
                        })
                        return result
                    }
                }
            })
        },
        setProjectOptions() {
            const data = {
                roadCode: this.info.roadCode,
                year: this.form.year,
                month: this.form.month
            }
            this.model.getRelatedProject(data).then(res => {
                this.projectOptions = res
            })
        },
        show(row) {
            this.info = row
            this.handleDisabledDate(row.roadCode)
            this.form.arithmeticalUnit = row.arithmeticalUnit
            this.$emit('update:visible', true)
            this.$nextTick(() => {
                this.$refs['dialogForm'].clearValidate()
            })
        },
        handleAdd() {
            this.$refs['dialogForm'].validate(valid => {
                if (valid) {
                    this.submitLoading = true
                    const data = Object.assign({ ...this.form }, { gcId: this.info.id })
                    
                    this.progressModel.saveOrUpdate(data).then(() => {
                        this.$message.success('更新成功!')
                        // 通知父组件已经更新完毕，做回调操作
                        this.$emit('submit')
                        this.handleCancel()
                    }).finally(() => {
                        this.submitLoading = false
                    })
                }
            })
        },
        handleCancel() {
            this.form = {}
            this.$emit('update:visible', false)
        },
        validNum(rule, value, callback) {
            console.log(value)
            if (value < 0 || value > 100) {
                callback(new Error('进度限制0-100'))
            } else {
                callback()
            }
        },
        validNum2(rule, value, callback) {
            if (value && !isNumber2(value)) {
                callback(new Error('填写格式错误'))
            } else {
                callback()
            }
        },
        validNum6(rule, value, callback) {
            if (value && !isNumber6(value)) {
                callback(new Error('填写格式错误'))
            } else {
                callback()
            }
        }
    }
}
</script>

<style lang="scss" scoped>
</style>
